<template>
  <div>
    <!--1视图-->
    <el-container>
      <span>当前在线人:{{uname}},角色:{{role}}</span>
      <el-header style="text-align: right; font-size: 30px">
        <el-dropdown @command="handleCommand" >
          <i style="margin-right: 14px" class="el-icon-more"></i>
          <span>
            <el-avatar shape="square" :src="circleUrl" :size="60"></el-avatar>
          </span>
          <i style="margin-right: 14px"></i>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="a" type="primary" icon="el-icon-s-tools">用户设置</el-dropdown-item>
            <el-dropdown-item command="b" type="primary" icon="el-icon-view">个人主页</el-dropdown-item>
            <el-dropdown-item command="c" type="primary" icon="el-icon-user-solid">退出登录</el-dropdown-item>
            <el-dropdown-item command="d" type="primary" icon="el-icon-headset">播放音乐</el-dropdown-item>
            <el-dropdown-item command="e" type="primary" icon="el-icon-video-play">暂停音乐</el-dropdown-item>
            <el-dropdown-item command="f" type="primary" icon="el-icon-refresh">切换音乐</el-dropdown-item>
            <el-dropdown-item>
              <span>当前在线人数:{{people}}</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-header>
      <el-container>

      <el-aside width="200px"> <el-menu
          :unique-opened="true"
          background-color="#304156"
          :collapse-transition="false"
          text-color="#bfcbd9"
          default-active="2"
          mode="vertical"
          class="el-menu-vertical-demo" router>
        <el-submenu v-for="m in menus" :index="m.id" v-bind:key="m.id" >
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>{{m.name}}</span>
          </template>
          <el-menu-item-group>
            <el-menu-item :index="c.path" v-for="c in m.children" v-bind:key="c.id">{{c.name}}</el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </el-menu>
      </el-aside>
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
    </el-container>


    <el-dialog title="个人主页" :visible.sync="dialogFormVisible">
      <el-descriptions title="用户信息">
        <el-descriptions-item label="头像">
          <el-avatar shape="square" :src="circleUrl" :size="100"></el-avatar>
        </el-descriptions-item>
        <el-descriptions-item label="用户名">{{ form.uname }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ form.tel }}</el-descriptions-item>
        <el-descriptions-item label="账号创建时间">{{ form.createDate }}</el-descriptions-item>
        <el-descriptions-item label="权限">
          <el-tag size="small">{{ form.name }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">账号设置</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>


import axios from "axios";

export default {
  name: "IndexView",
  data() {
    return {
      musicUrl:'',
      musicList: [
        { src: "hk.mp3" },
        { src: "music1.mp3" },
        { src: "莫问归期.mp3" },
        { src: "欢乐斗地主.mp3" },
        { src: "ForYa.mp3" },
        { src: "最远的你是我最近的爱.mp3" },
      ],
      currentMusicIndex: 0,
      uname:sessionStorage.getItem("uname"),
      role:sessionStorage.getItem("role"),
      token:localStorage.getItem("token"),
      //2属性定义
      menus:[],
      people: '',
      user:sessionStorage.getItem('user'),
      circleUrl: "https://foruda.gitee.com/avatar/1696571274093678534/13469108_wang-ruidongaaa_1696571274.png",
      dialogFormVisible: false,
      form: {},
      formLabelWidth: '120px'
    }
  }, methods: {

    ifOnline(){
      this.axios.get('/user/user/getonline?token='+this.token).then(res=>{
        if(res.data.code==200){
          this.$message.success(res.data.msg);
        }else{
          this.$message.error(res.data.msg);
          localStorage.removeItem("token");
          this.$router.push("/login");
        }
      })
    },
    ifexprie(){
      this.axios.get('/user/user/ifexprie?token='+this.token).then(res=>{
        if(res.data.code==200){
          this.$message.success(res.data.msg);
        }else{
          this.$message.error(res.data.msg);
          localStorage.removeItem("token");
          this.$router.push("/login");
        }
      })
    },
    //3自定义方法
    list(){
      this.axios.post("/menuservice/menu/list").then(res=>{
        this.menus=res.data.data;
      })
    },
    //登录人数获取方法

    getPeople(){
      this.axios.get('/user/user/count').then(res=>{
        console.log(res.data.data)
        this.people = res.data.data;
      })
    },

    handleCommand(command) {
      let  token = localStorage.getItem('token')
      if (command == 'a'){
        //用户设置
        this.axios.get('/user/user/getSetUp?token='+token).then(res=>{
          console.log(res.data)
        })
      }else if (command == 'b'){
        //查看详情
        // this.axios.post('/user/user/getDetails?token='+token).then(res=>{
        //   this.form = res.data.data;
        //   this.dialogFormVisible = true;
        // })
        this.$router.push('/tharPerson');
      }else if (command == 'c'){
        //退出登录
        this.axios.get('/user/user/outLogin?token='+token).then(res=>{
          this.$message.success(res.data.data);
          this.$router.push('/login')
        })
      }else if (command == 'd'){
        //播放音乐
        let music1 = new Audio();
        music1 = require("../assets/music/music1.mp3");
        this.$refs.musicPlayer.src = music1;
        this.$refs.musicPlayer.play();
      }else if (command == 'e'){
        //暂停音乐
        this.$refs.musicPlayer.pause();
      }else if (command == 'f'){
        var audio = document.getElementById('audio');
        let temp = this.index;
        while(this.index==temp){
          //你有几首歌曲在后面*n 序列是从0开始的
          this.index = parseInt(Math.random()*7);
          console.log(this.index);
        }
        this.musicUrl = require("../assets/music/" + this.musicList[this.index].src)
        audio.play();  // 播放
      }
    },
    startPolling() {
      this.pollInterval = setInterval(() => {
        console.log('Polling for latest result...');
        this.fetchLatestResult();
      }, 3000);
    },
    startPolling2() {
      this.pollInterval2 = setInterval(() => {
        console.log('Polling for latest result...');
        this.fetchLatestResult2();
      }, 3000);
    },
    async fetchLatestResult() {
      try {
        const response = await axios.post('/user/user/dlatest');
        const data = response.data;
        console.log("cdvknvkfnvfnvkf"+JSON.stringify(data, null, 2));
        this.hasNewResult = data.data.hasNewResult; // 假设API返回的对象中包含这个字段
        this.message = data.data.message; // 假设API返回的对象中包含这个字段
        if (this.hasNewResult) {
          // 显示通知或执行其他逻辑
          alert(data.data.message);
          clearInterval(this.pollInterval);
          this.$router.push("/ding")

        }
      } catch (error) {
        console.error('Error fetching result:', error);
      }
    },
    async fetchLatestResult2() {
      try {
        const response = await axios.post('/cropservice/crop/latest');
        const data = response.data;
        console.log("cdvknvkfnvfnvkf"+JSON.stringify(data, null, 2));
        this.hasNewResult = data.data.hasNewResult; // 假设API返回的对象中包含这个字段
        this.message = data.data.message; // 假设API返回的对象中包含这个字段
        if (this.hasNewResult) {
          // 显示通知或执行其他逻辑
          alert(data.data.message);
          this.$router.push("/ding")
          clearInterval(this.pollInterval2);
        }
      } catch (error) {
        console.error('Error fetching result:', error);
      }
    },
  },
  mounted() {
    this.ifOnline();
    //是否过期
    this.ifexprie();
  }
  , created() {
    //4.钩子函数
    this.list();
    this.getPeople();
    this.startPolling();
    this.startPolling2();
  },
  beforeDestroy() {
    // 在组件销毁前清除定时器，避免内存泄漏
    clearInterval(this.pollInterval);
    clearInterval(this.pollInterval2);
  },
}
</script>

<style scoped>
.top {
  display: flex;
  justify-content: center;   /* 水平居中 */
}
.card-footer {
  text-align: right;
  font-size: 14px;
  color: #999;
}



body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
.el-header {
  background-color: #B3C0D1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
</style>